/*
 * 
 * 
 * 
 */
package com.hboxs.asl.filter;

import com.hboxs.asl.entity.Merchant;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Filter - 商家状态过滤器
 */
public class MerchantFilter implements Filter {


    /**
     * 默认忽略URL
     */
    private static final String[] DEFAULT_IGNORE_URL_PATTERNS = new String[]{};

    /**
     * 默认重定向URL
     */
    private static final String DEFAULT_REDIRECT_URL = "/asl-merchant/merchant/login.htm";

    /**
     * 忽略URL
     */
    private String[] ignoreUrlPatterns = DEFAULT_IGNORE_URL_PATTERNS;

    /**
     * antPathMatcher
     */
    private static AntPathMatcher antPathMatcher = new AntPathMatcher();

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void destroy() {
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();

        String path = request.getRequestURI();

        if (path.equals(DEFAULT_REDIRECT_URL)) {
            filterChain.doFilter(request, response);
            return;
        }
        if (ignoreUrlPatterns != null) {
            for (String ignoreUrlPattern : ignoreUrlPatterns) {
                if (antPathMatcher.match(ignoreUrlPattern, path)) {
                    filterChain.doFilter(request, response);
                    return;
                }
            }
        }

        if(session.getAttribute(Merchant.SESSION_KEY)==null){
            response.sendRedirect(request.getContextPath() + DEFAULT_REDIRECT_URL);
        }else{
            filterChain.doFilter(request, response);
        }

    }

}